import React, { useState, useMemo } from 'react';
import { Resizable } from 'react-resizable';
import moment from 'moment';
import { Table } from 'antd';
import { InbizIcon } from '@inbiz/utils';
import ProcessLogModal from '../ProcessLogModal';
import { getLogInfo, clickRow } from '../../utils';
import { processState, goto, goPopupDetail, goDrawerDetail, getProcessInfoAfterCustomClickItem } from '../../../commonUtils';
import { observer } from '@formily/react';
import { TextWidget, getMessage } from '@inbiz/react';
import './index.less';

const dateFormat = 'YYYY-MM-DD HH:mm:ss';

const ResizableTitle = (
  props: React.HTMLAttributes<any> & {
    onResize: (e: React.SyntheticEvent<Element>, data) => void;
    width: number;
  },
) => {
  const { onResize, width, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      handle={
        <span
          className="react-resizable-handle"
          onClick={(e) => {
            e.stopPropagation();
          }}
        />
      }
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} />
    </Resizable>
  );
};

export default observer((props: any) => {
  const {
    rowSelection,
    choosedTabKey,
    choosedItem,
    delDraft,
    getList,
    infoList,
    pageData,
    searchText,
    condition,
    searchApplyList,
    openMode,
    openPopUpHeight,
    openPopUpWidth,
    drawerWidth,
    setLoading,
    customClickItem,
  } = props;

  const [logVisible, $logVisible] = useState(false);
  const [logInfo, $logInfo] = useState({
    instanceId: '',
    processId: '',
  });

  const myGetLogInfo = (e, record) => {
    getLogInfo(
      e,
      {
        taskIds: record.taskId,
        processInstanceId: record.processInstanceId,
        inItiateApplication: false,
        taskState: record.taskState,
        siteType: 3,
      },
      $logVisible,
      $logInfo,
    );
  };

  const myGoto = async (e, record, inItiateApplication, index) => {
    if (customClickItem) {
      const params = choosedTabKey == '4' ? {
        processDefinitionId: record.procDefId,
        businessKey: record.businessKey,
        drafID: record.draftsId,
        inItiateApplication: true,
        taskState: record.taskState,
        siteType: 0,
      } : {
        taskIds: record.taskId,
        processInstanceId: record.processInstanceId,
        inItiateApplication: false,
        drafID: record.draftsId,
        taskState: record.taskState,
        siteType: 0,
      };
      const result = await getProcessInfoAfterCustomClickItem(params);
      customClickItem({ event: e, processItem: record, requestItem: result });
      return;
    }
    let _callback = async () => {
      await getList(
        infoList?.length == 1 && pageData.pageIndex != 1 ? pageData.pageIndex - 1 : pageData.pageIndex,
        pageData.pageSize,
        choosedTabKey,
        searchText,
        condition,
        () => {
          if (choosedTabKey == 2 && infoList?.length >= 10) {
            setTimeout(() => {
              let _wrapper = document.getElementsByClassName('inbiz-processCenter-table')[0];
              if (_wrapper) {
                let _scrollBody = _wrapper.getElementsByClassName('ant-table-tbody')[0];
                let _item =
                  _scrollBody.getElementsByTagName('tr')[
                  infoList?.length > (index || 0) ? index : infoList?.length
                  ];
                _item.scrollIntoView();
              }
            }, 0);
          }
        },
      );
      searchApplyList(choosedTabKey);
    };
    if (openMode == 'newPage') {
      goto(
        {
          taskIds: record.taskId,
          processInstanceId: record.processInstanceId,
          inItiateApplication,
          taskState: record.taskState,
          siteType: 0,
        },
        choosedTabKey,
        'web',
        e,
        '',
        _callback,
        setLoading,
      );
    } else if (openMode == 'popUp') {
      goPopupDetail(record, choosedTabKey, openPopUpHeight, openPopUpWidth, setLoading, _callback);
    } else if (openMode == 'rightDrawer') {
      goDrawerDetail(record, choosedTabKey, drawerWidth, setLoading, _callback);
    }
  };

  const rowId = useMemo(() => {
    switch (choosedTabKey) {
      case '2':
      case '5':
      case '7':
      case '8':
        return 'taskId';
      case '3':
      case '6':
        return 'processInstanceId';
      case '4':
        return 'draftsId';
      default:
        return ''
    }
  }, [choosedTabKey]);

  const initcolumn: any = () => {
    switch (choosedTabKey) {
      case '2':
        return [
          {
            width: '5%',
            dataIndex: 'proLcon',
            ellipsis: true,
            render: (text, record) => (
              <div className="operation" onClick={(e) => myGetLogInfo(e, record)}>
                <InbizIcon
                  type="icon-process-liuchengrizhi"
                  style={{ fontSize: 20, color: '#666' }}
                />
              </div>
            ),
          },
          {
            width: '6%',
            title: getMessage('ProcessCenter.status'),
            dataIndex: 'taskState',
            ellipsis: true,
            render: (text) => (
              <div
                style={{
                  width: 52,
                  height: 24,
                  color: processState[text].stateFontColor ?? '',
                  background: processState[text].stateBgColor || '',
                  lineHeight: '24px',
                  borderRadius: '4px',
                  textAlign: 'center',
                  fontSize: 12,
                }}
              >
                <TextWidget>
                  {text ? processState[text].stateName : processState['0'].stateName}
                </TextWidget>
              </div>
            ),
          },
          {
            width: '11%',
            title: getMessage('ProcessCenter.instanceNumber'),
            dataIndex: 'processInstanceId',
            ellipsis: true,
          },
          {
            width: '11%',
            title: getMessage('ProcessCenter.processName'),
            dataIndex: 'processName',
            ellipsis: true,
            render: (text, record, index) => {
              return (
                <div className="operation" onClick={(e) => { myGoto(e, record, false, index); }}>
                  {text}
                </div>
              );
            },
          },
          {
            width: '11%',
            title: getMessage('ProcessCenter.taskName'),
            dataIndex: 'stepName',
            ellipsis: true,
          },
          {
            width: '11%',
            title: getMessage('ProcessCenter.starter'),
            dataIndex: 'initiatorName',
            ellipsis: true,
          },
          {
            width: '18%',
            title: getMessage('ProcessCenter.processArrivalTime'),
            ellipsis: true,
            dataIndex: 'taskCreateTime',
            render: (text) => {
              return moment(text).format(dateFormat);
            },
          },
          {
            title: getMessage('ProcessCenter.summary'),
            dataIndex: 'summary',
            ellipsis: true,
          },
        ];
      case '3':
        return [
          {
            width: '6%',
            dataIndex: 'proLcon',
            ellipsis: true,
            render: (text, record) => (
              <div className="operation" onClick={(e) => myGetLogInfo(e, record)}>
                <InbizIcon
                  type="icon-process-liuchengrizhi"
                  style={{ fontSize: 20, color: '#666' }}
                />
              </div>
            ),
          },
          {
            width: '8%',
            title: getMessage('ProcessCenter.status'),
            dataIndex: 'taskState',
            ellipsis: true,
            render: (text) => (
              <div
                style={{
                  width: 52,
                  height: 24,
                  color: processState[text].stateFontColor ?? '',
                  background: processState[text].stateBgColor || '',
                  lineHeight: '24px',
                  borderRadius: '4px',
                  textAlign: 'center',
                  fontSize: 12,
                }}
              >
                <TextWidget>
                  {text ? processState[text].stateName : processState['0'].stateName}
                </TextWidget>
              </div>
            ),
          },
          {
            width: '12%',
            title: getMessage('ProcessCenter.instanceNumber'),
            dataIndex: 'processInstanceId',
            ellipsis: true,
          },
          {
            width: '12%',
            title: getMessage('ProcessCenter.processName'),
            dataIndex: 'processName',
            ellipsis: true,
            render: (text, record, index) => {
              return (
                <div className="operation" onClick={(e) => myGoto(e, record, false, index)}>
                  {text}
                </div>
              );
            },
          },
          {
            width: '12%',
            title: getMessage('ProcessCenter.starter'),
            dataIndex: 'startName',
            ellipsis: true,
          },
          {
            width: '18%',
            title: getMessage('ProcessCenter.processStartTime'),
            ellipsis: true,
            dataIndex: 'processStartTime',
            render: (text) => moment(text).format(dateFormat),
          },
          {
            title: getMessage('ProcessCenter.summary'),
            dataIndex: 'summary',
            ellipsis: true,
          },
        ];
      case '4':
        return [
          {
            title: getMessage('ProcessCenter.status'),
            dataIndex: 'taskState',
            ellipsis: true,
            render: (text) => getMessage('processCenter.draft'),
          },
          {
            width: '50%',
            title: getMessage('processCenter.processName'),
            dataIndex: 'processName',
            ellipsis: true,
            render: (text, record) => (
              <span
                className="operation"
                onClick={async (e) => {
                  if (customClickItem) {
                    const params = choosedTabKey == '4' ? {
                      processDefinitionId: record.procDefId,
                      businessKey: record.businessKey,
                      drafID: record.draftsId,
                      inItiateApplication: true,
                      taskState: record.taskState,
                      siteType: 0,
                    } : {
                      taskIds: record.taskId,
                      processInstanceId: record.processInstanceId,
                      inItiateApplication: false,
                      drafID: record.draftsId,
                      taskState: record.taskState,
                      siteType: 0,
                    };
                    const result = await getProcessInfoAfterCustomClickItem(params);
                    customClickItem({ event: e, processItem: record, requestItem: result });
                    return;
                  }
                  let _callback = async () => {
                    searchApplyList(choosedTabKey);
                    await getList(
                      infoList?.length == 1 && pageData.pageIndex != 1
                        ? pageData.pageIndex - 1
                        : pageData.pageIndex,
                      pageData.pageSize,
                      choosedTabKey,
                      searchText,
                      condition,
                    );
                  };
                  if (openMode == 'newPage') {
                    goto(
                      {
                        processDefinitionId: record.procDefId,
                        businessKey: record.businessKey,
                        drafID: record.draftsId,
                        inItiateApplication: true,
                        taskState: record.taskState,
                        siteType: 0,
                      },
                      '4',
                      'web',
                      e,
                      '',
                      _callback,
                      setLoading,
                    );
                  } else if (openMode == 'popUp') {
                    goPopupDetail(record, choosedTabKey, openPopUpHeight, openPopUpWidth, setLoading, _callback);
                  } else if (openMode == 'rightDrawer') {
                    goDrawerDetail(record, choosedTabKey, drawerWidth, setLoading, _callback);
                  }
                }}
              >
                {text}
              </span>
            ),
          },
          {
            width: '20%',
            title: getMessage('processCenter.createTime'),
            ellipsis: true,
            dataIndex: 'creationTime',
            render: (text) => moment(text).format(dateFormat),
          },
          {
            width: '20%',
            title: getMessage('processCenter.operate'),
            dataIndex: '',
            ellipsis: true,
            render: (text, record) => {
              return (
                <div>
                  <span
                    className="operation"
                    style={{ marginRight: 20 }}
                    onClick={(e) => delDraft(e, record)}
                  >
                    <TextWidget>global.delete</TextWidget>
                  </span>
                  <span
                    className="operation"
                    onClick={(e) => {
                      let _callback = async () => {
                        searchApplyList(choosedTabKey);
                        await getList(
                          list?.length == 1 && pageData.pageIndex != 1
                            ? pageData.pageIndex - 1
                            : pageData.pageIndex,
                          pageData.pageSize,
                          choosedTabKey,
                          searchText,
                          condition,
                        );
                      };
                      if (openMode == 'newPage') {
                        goto(
                          {
                            processDefinitionId: record.procDefId,
                            businessKey: record.businessKey,
                            drafID: record.draftsId,
                            inItiateApplication: true,
                            taskState: record.taskState,
                            siteType: 0,
                          },
                          '4',
                          'web',
                          e,
                          '',
                          _callback,
                          setLoading,
                        );
                      } else if (openMode == 'popUp') {
                        goPopupDetail(
                          record,
                          choosedTabKey,
                          openPopUpHeight,
                          openPopUpWidth,
                          setLoading,
                          _callback,
                        );
                      } else if (openMode == 'rightDrawer') {
                        goDrawerDetail(record, choosedTabKey, drawerWidth, setLoading, _callback);
                      }
                    }}
                  >
                    <TextWidget>global.edit</TextWidget>
                  </span>
                </div>
              );
            },
          },
        ];
      case '5':
        return [
          {
            width: '5%',
            dataIndex: 'proLcon',
            ellipsis: true,
            render: (text, record) => (
              <div className="operation" onClick={(e) => myGetLogInfo(e, record)}>
                <InbizIcon
                  type="icon-process-liuchengrizhi"
                  style={{ fontSize: 20, color: '#666' }}
                />
              </div>
            ),
          },
          {
            width: '8%',
            title: getMessage('ProcessCenter.status'),
            dataIndex: 'taskState',
            ellipsis: true,
            render: (text) => (
              <div
                style={{
                  width: 52,
                  height: 24,
                  color: processState[text].stateFontColor ?? '',
                  background: processState[text].stateBgColor || '',
                  lineHeight: '24px',
                  borderRadius: '4px',
                  textAlign: 'center',
                  fontSize: 12,
                }}
              >
                <TextWidget>
                  {text ? processState[text].stateName : processState['0'].stateName}
                </TextWidget>
              </div>
            ),
          },
          {
            width: '11%',
            title: getMessage('ProcessCenter.instanceNumber'),
            dataIndex: 'processInstanceId',
            ellipsis: true,
          },
          {
            width: '11%',
            title: getMessage('ProcessCenter.processName'),
            dataIndex: 'processName',
            ellipsis: true,
            render: (text, record, index) => {
              return (
                <div className="operation" onClick={(e) => myGoto(e, record, false, index)}>
                  {text}
                </div>
              );
            },
          },
          {
            width: '11%',
            title: getMessage('ProcessCenter.taskName'),
            dataIndex: 'stepName',
            ellipsis: true,
          },
          {
            width: '11%',
            title: getMessage('processCenter.starterName'),
            dataIndex: 'starterName',
            ellipsis: true,
          },
          {
            width: '18%',
            title: getMessage('ProcessCenter.processArrivalTime'),
            dataIndex: 'taskStartTime',
            ellipsis: true,
            render: (text) => moment(text).format(dateFormat),
          },
          {
            title: getMessage('ProcessCenter.summary'),
            dataIndex: 'summary',
            ellipsis: true,
          },
        ];
      case '6':
        return [
          {
            width: '6%',
            dataIndex: 'proLcon',
            ellipsis: true,
            render: (text, record) => (
              <div className="operation" onClick={(e) => myGetLogInfo(e, record)}>
                <InbizIcon
                  type="icon-process-liuchengrizhi"
                  style={{ fontSize: 20, color: '#666' }}
                />
              </div>
            ),
          },
          {
            width: '8%',
            title: getMessage('ProcessCenter.status'),
            dataIndex: 'taskState',
            ellipsis: true,
            render: (text) => (
              <div
                style={{
                  width: 52,
                  height: 24,
                  color: processState[text].stateFontColor ?? '',
                  background: processState[text].stateBgColor || '',
                  lineHeight: '24px',
                  borderRadius: '4px',
                  textAlign: 'center',
                  fontSize: 12,
                }}
              >
                <TextWidget>
                  {text ? processState[text].stateName : processState['0'].stateName}
                </TextWidget>
              </div>
            ),
          },
          {
            width: '12%',
            title: getMessage('ProcessCenter.instanceNumber'),
            dataIndex: 'processInstanceId',
            ellipsis: true,
          },
          {
            width: '12%',
            title: getMessage('ProcessCenter.processName'),
            ellipsis: true,
            dataIndex: 'processName',
            render: (text, record, index) => {
              return (
                <div className="operation" onClick={(e) => myGoto(e, record, false, index)}>
                  {text}
                </div>
              );
            },
          },
          {
            width: '12%',
            title: getMessage('ProcessCenter.starter'),
            ellipsis: true,
            dataIndex: 'startName',
          },
          {
            width: '20%',
            title: getMessage('ProcessCenter.processStartTime'),
            ellipsis: true,
            dataIndex: 'processStartTime',
            render: (text) => moment(text).format(dateFormat),
          },
          {
            title: getMessage('ProcessCenter.summary'),
            dataIndex: 'summary',
            ellipsis: true,
          },
        ];
      case '7':
        return [
          {
            width: '5%',
            dataIndex: 'proLcon',
            ellipsis: true,
            render: (text, record) => (
              <div className="operation" onClick={(e) => myGetLogInfo(e, record)}>
                <InbizIcon
                  type="icon-process-liuchengrizhi"
                  style={{ fontSize: 20, color: '#666' }}
                />
              </div>
            ),
          },
          {
            width: '6%',
            title: getMessage('ProcessCenter.status'),
            dataIndex: 'taskState',
            ellipsis: true,
            render: (text) => (
              <div
                style={{
                  width: 52,
                  height: 24,
                  color: processState[text].stateFontColor ?? '',
                  background: processState[text].stateBgColor || '',
                  lineHeight: '24px',
                  borderRadius: '4px',
                  textAlign: 'center',
                  fontSize: 12,
                }}
              >
                <TextWidget>
                  {text ? processState[text].stateName : processState['0'].stateName}
                </TextWidget>
              </div>
            ),
          },
          {
            width: '10%',
            title: getMessage('ProcessCenter.instanceNumber'),
            dataIndex: 'processInstanceId',
            ellipsis: true,
          },
          {
            width: '10%',
            title: getMessage('ProcessCenter.processName'),
            dataIndex: 'processName',
            ellipsis: true,
            render: (text, record, index) => {
              return (
                <div className="operation" onClick={(e) => myGoto(e, record, false, index)}>
                  {text}
                </div>
              );
            },
          },
          {
            width: '10%',
            title: getMessage('ProcessCenter.taskName'),
            dataIndex: 'stepName',
            ellipsis: true,
          },
          {
            width: '10%',
            title: getMessage('ProcessCenter.starter'),
            dataIndex: 'initiatorName',
            ellipsis: true,
          },
          {
            width: '14%',
            title: getMessage('ProcessCenter.processArrivalTime'),
            dataIndex: 'taskCreateTime',
            ellipsis: true,
            render: (text) => moment(text).format(dateFormat),
          },
          {
            width: '14%',
            title: getMessage('processCenter.processEndTime'),
            ellipsis: true,
            dataIndex: 'taskCompleteTime',
            render: (text) => moment(text).format(dateFormat),
          },
          {
            title: getMessage('ProcessCenter.summary'),
            dataIndex: 'summary',
            ellipsis: true,
          },
        ];
      case '8':
        return [
          {
            width: '7%',
            dataIndex: 'proLcon',
            ellipsis: true,
            render: (text, record) => (
              <div className="operation" onClick={(e) => myGetLogInfo(e, record)}>
                <InbizIcon
                  type="icon-process-liuchengrizhi"
                  style={{ fontSize: 20, color: '#666' }}
                />
              </div>
            ),
          },
          {
            width: '9%',
            title: getMessage('ProcessCenter.status'),
            dataIndex: 'taskState',
            ellipsis: true,
            render: (text) => (
              <div
                style={{
                  width: 52,
                  height: 24,
                  color: processState[text].stateFontColor ?? '',
                  background: processState[text].stateBgColor || '',
                  lineHeight: '24px',
                  borderRadius: '4px',
                  textAlign: 'center',
                  fontSize: 12,
                }}
              >
                <TextWidget>
                  {text ? processState[text].stateName : processState['0'].stateName}
                </TextWidget>
              </div>
            ),
          },
          {
            width: '11%',
            title: getMessage('ProcessCenter.instanceNumber'),
            dataIndex: 'processInstanceId',
            ellipsis: true,
          },
          {
            width: '11%',
            title: getMessage('ProcessCenter.processName'),
            dataIndex: 'processName',
            ellipsis: true,
            render: (text, record, index) => {
              return (
                <div className="operation" onClick={(e) => myGoto(e, record, false, index)}>
                  {text}
                </div>
              );
            },
          },
          // {
          //   width: '8%',
          //   title: getMessage('ProcessCenter.taskName'),
          //   dataIndex: 'stepName',
          //   ellipsis: true,
          // },
          {
            width: '10%',
            title: getMessage('ProcessCenter.starter'),
            dataIndex: 'initiatorName',
            ellipsis: true,
          },
          {
            width: '15%',
            title: getMessage('ProcessCenter.processStartTime'),
            ellipsis: true,
            dataIndex: 'processCreateTime',
            render: (text) => moment(text).format(dateFormat),
          },
          {
            width: '15%',
            ellipsis: true,
            title: getMessage('processCenter.processEndTime'),
            dataIndex: 'processCompleteTime',
            render: (text) => moment(text).format(dateFormat),
          },
          // {
          //   width: '12%',
          //   title: getMessage('processCenter.comment'),
          //   dataIndex: 'taskComment',
          //   ellipsis: true,
          // },
          {
            title: getMessage('ProcessCenter.summary'),
            dataIndex: 'summary',
            ellipsis: true,
          },
        ];
      default:
        return [];
    }
  }

  // const [columns, $columns] = useState(initcolumn);

  // const handleResize =
  //   (index: number) =>
  //     (_: React.SyntheticEvent<Element>, { size }) => {
  //       const newColumns = [...columns];
  //       newColumns[index] = {
  //         ...newColumns[index],
  //         width: size.width,
  //       };
  //       $columns(newColumns);
  //     };

  // const mergeColumns = useMemo(() => {
  //   return columns.map((col, index) => ({
  //     ...col,
  //     onHeaderCell: (column) => ({
  //       width: column.width,
  //       onResize: handleResize(index),
  //     }),
  //   }));
  // }, [columns, handleResize, choosedTabKey, processState, dateFormat, searchText, condition, openMode, pageData, infoList, myGoto])

  return (
    <>
      {
        rowId && initcolumn() && initcolumn()?.length > 0
        && infoList && infoList?.length > 0 &&
        <>
          <Table
            className="inbiz-processCenter-table"
            columns={initcolumn()}
            dataSource={infoList}
            pagination={false}
            rowSelection={rowSelection}
            rowKey={rowId}
            scroll={{ y: 'calc(100% - 40px)' }}
            // components={{
            //   header: {
            //     cell: ResizableTitle,
            //   },
            // }}
            onRow={(record) => {
              return {
                onClick: () => {
                  clickRow(record, rowSelection, choosedTabKey == '2' ?? false, choosedItem);
                },
              };
            }}
          />
          <ProcessLogModal visible={logVisible} $visible={$logVisible} logInfo={logInfo} />
        </>
      }
    </>
  );
});
